<template>
  <div style="width: 100%">
    <el-dialog :append-to-body="true" destroy-on-close :title="title" width="1000px" :visible.sync="visible">
      <div style="width: 100%">
        <avue-crud :option="option"
                   :table-loading="loading"
                   :data="tableData"
                   :page.sync="page"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @selection-change="selectionChange"
                   ref="crud">
          <template slot-scope="{row}" slot="interfaceAttribute">
            {{ interfaceAttribute(row) }}
          </template>
        </avue-crud>
      </div>
      <div slot="footer" style="text-align: center">
        <el-button size="medium" type="primary" @click="addToList">添加</el-button>
        <el-button size="medium" @click="visible=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/router/axios';

export default {
  name: "getDataCommonDialog",
  props: {
    column: {
      required: true,
      type: Array,
      default: () => {
        return []
      }
    },
    url: {
      type: String,
      default: () => {
        return ""
      }
    },
    sourceData: {
      type: Array,
      default: () => {
        return []
      }
    },
    param: {
      type: Object,
      default: () => {
        return {}
      }
    },
    title: {
      required: true,
      type: String,
      default: () => {
        return "标题"
      }
    },
    // 限制选择数量
    limit: {
      type: Number,
      default: () => {
        return 9999
      }
    },
    // 是否分页
    isPage: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    // 主键id
    idKey: {
      type: String,
      default: () => {
        return "oid"
      }
    },
  },
  data() {
    return {
      visible: false,

      page: {
        pageSize: 10,
        currentPage: 1,
        total: 1
      },
      tableData: [],
      loading: false,
      option: {
        height: '400px',
        calcHeight: 30,
        dialogWidth: 900,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        selection: true,
        labelWidth: 120,
        menuWidth: 200,
        viewBtn: false,
        dialogClickModal: false,
        tabs: true,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false,
        align: "left",
        menu: false,
        header: false,
        selectable: (row) => {
          return !(row.extendsFlag === 1);
        },
        column: this.column
      },

      selection: [],
      // 回选的list
      recirculationSelection: [],

      //固定选中不能修改选中的list
      checkedList: [],
    }
  },
  methods: {
    selectionChange(selection) {
      // 限制单选只能选一个
      if (this.limit === 1 && selection.length !== 1) {
        const val = selection.shift();
        this.$refs["crud"].toggleRowSelection(val, false);
      }
      this.selection = selection;
    },
    interfaceAttribute(row) {
      if (row.extAttributes && row.extAttributes.length > 0) {
        return row.extAttributes.map(i => i.nameCn).join("，");
      }
      return "";
    },

    addToList() {
      if (this.selection.length === 0) {
        this.$message.warning("请选择数据");
        return;
      }
      if (this.checkedList.length > 0 && this.checkedList.length === this.selection.length) {
        this.$message.warning("请选择数据");
        return;
      }
      if (this.limit < this.selection.length) {
        this.$message.warning("选择数量不可超过" + this.limit + "个");
        return;
      }
      this.$emit('addToList', this.deepCopy(this.selection));
    },
    /**
     * @param list 回选的数据集合
     * */
    open(list, checkedList = []) {
      this.checkedList = checkedList;
      this.page = {pageSize: 10, currentPage: 1};
      this.recirculationSelection = list;
      this.getList();
    },
    toggleRowSelection() {
      if (this.tableData && this.tableData.length > 0 && this.recirculationSelection && this.recirculationSelection.length > 0) {
        this.selection = [];
        let ids = this.recirculationSelection.map(item => item[this.idKey]);
        // 说明此列表不存在 oid
        // 整行数据转为 String 进行对比匹配
        let checkedIds = this.checkedList.map(item => item.oid);
        if (!ids[0]) {
          let recirculationSelection = this.recirculationSelection.map(item => JSON.stringify(item));

          this.tableData.forEach(item => {
            if (checkedIds.includes(item.oid)) {
              item.extendsFlag = 1;
            }
            if (recirculationSelection.includes(JSON.stringify(item))) {
              this.$refs.crud.toggleRowSelection(item, true);
            }
          })
        } else {
          this.tableData.forEach(item => {
            if (checkedIds.includes(item.oid)) {
              item.extendsFlag = 1;
            }
            if (ids.includes(item[this.idKey])) {
              this.$refs.crud.toggleRowSelection(item, true);
            }
          })
        }
      }
    },
    close() {
      this.visible = false;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.getList();

    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getList();
    },
    getList() {
      if (!this.url) {
        this.visible = true;
        this.tableData = this.deepCopy(this.sourceData);
        this.$nextTick(() => {
          this.toggleRowSelection();
        })
        return;
      }
      let param = {};
      if (this.isPage) {
        param = {current: this.page.currentPage, size: this.page.pageSize,}
      }
      request({
        url: this.url,
        method: 'get',
        params: {
          ...param,
          ...this.param
        }
      }).then(res => {

        if (this.isPage) {
          const {list, totalRows} = res.data.data;
          this.tableData = list;
          this.page.total = totalRows;
        } else {
          this.tableData = res.data.data;
        }

        this.visible = true;
        this.$nextTick(() => {
          this.toggleRowSelection();
        })
      })
    }
  }
}
</script>
<style scoped>

</style>
